import { plugin, Messagetype } from 'alemon'
import db from '../../db/sqlite/config.js'
import dayjs from '../../lib/day.js'
import { join } from 'path'
import { MyDirPath } from '../../app.config.js'
import { obtainingImages } from '../../lib/img/index.js'
import { QueryTypes } from 'sequelize'
export class K_打卡 extends plugin {
  constructor() {
    super({
      dsc: '打卡',
      rule: [
        {
          reg: '^/打卡$',
          fnc: '打卡'
        },
        {
          reg: '^/早鸟榜$',
          fnc: '早鸟榜'
        }
      ]
    })

    // 创建表
    db.query(`CREATE TABLE IF NOT EXISTS k_daka
   (
     "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
     "guild" TEXT NOT NULL,
     "user_id" TEXT NOT NULL,
     "user_name" TEXT NOT NULL,
     "time" text NOT NULL
   )
`)
  }
  async 打卡(e: Messagetype) {
    //    需要私域或公域事件
    if (e.eventType !== 'CREATE' && e.event !== 'MESSAGES' && !e.isGroup) {
      return
    }

    const data = (await db
      .query('select * from k_daka where guild = ? and user_id = ? ', {
        replacements: [e.msg.guild_id, e.msg.author.id],
        type: QueryTypes.SELECT
      })
      .catch(err => err.parent)) as {
      id: number
      guild: string
      user_id: string
      user_name: string
      time: string
    }

    if ('errno' in data) {
      return e.reply('查询数据库失败')
    }

    const now = dayjs().format('YYYY-MM-DD HH:mm:ss')
    // console.log(data)

    // 存在
    if (data[0]) {
      // 签到那天结束的时间
      const start = dayjs(data[0].time, 'YYYY-MM-DD HH:mm:ss').endOf('day')
      //  当前时间
      const end = dayjs(now, 'YYYY-MM-DD HH:mm:ss')
      // 判断今天是否已经签到
      if (dayjs.duration(end.diff(start)).asDays() < 0) {
        return e.reply(`<@!${e.msg.author.id}> 您已打卡请明天再来`)
      } else {
        // 今天没有签到
        const y = await 打卡(e, now)
        // 更新数据库
        if (y)
          await db.query('UPDATE k_daka SET time = ? WHERE user_id = ?', {
            replacements: [now, e.msg.author.id],
            type: QueryTypes.UPDATE
          })
      }
    } else {
      // 不存在
      const y = await 打卡(e, now)

      // 添加一条数据
      if (y)
        await db.query('INSERT INTO k_daka (guild, user_id, user_name, time) VALUES (?, ?, ?, ?)', {
          replacements: [e.msg.guild_id, e.msg.author.id, e.msg.author.username, now],
          type: QueryTypes.INSERT
        })
    }

    return true
  }

  async 早鸟榜(e: Messagetype) {
    //    需要私域或公域事件
    if (e.eventType !== 'CREATE' && e.event !== 'MESSAGES' && !e.isGroup) {
      return
    }

    const data = (await db
      .query(
        `SELECT user_name, time  FROM "k_daka" WHERE "time" LIKE '%${dayjs().format(
          'YYYY-MM-DD'
        )}%' and guild=${e.msg.guild_id}  ORDER BY "time" ASC LIMIT 0,10`,
        { type: QueryTypes.SELECT }
      )
      .catch(err => err.parent)) as Array<{ user_name: string; time: string }>

    if ('errno' in data) {
      return e.reply('查询数据库失败')
    }

    if (data.length === 0) {
      return e.reply('这个频道都是一群懒鸟')
    } else {
      const list = ['今日早鸟榜\n']
      for (const item in data) {
        list.push(`第${Number(item) + 1}名：${data[item].user_name} 打卡时间：${data[item].time}\n`)
      }

      return e.reply(list)
    }
  }
}

async function 打卡(e: Messagetype, now: string) {
  const data = {
    img: e.msg.author.avatar,
    name: e.msg.author.username,
    time: now,
    path: join(MyDirPath, '/resources').replace(/\\/g, '/')
  }
  const img = await obtainingImages('', '打卡', data)

  if (img) {
    await e.postImage(img)
    return true
  } else {
    return false
  }
}
